package org.itsky.study.test4;

/**
 * @Author sky
 * @Site cmtianxie163.com 2020/4/16 15:50
 */

/**
 * 同步方法解决线程安全问题
 */
public class SynchronizedTest3 {
    public static void main(String[] args) {
        MyRunnable3 runnable3 = new MyRunnable3();
        Thread t1 = new Thread(runnable3);
        Thread t2 = new Thread(runnable3);
        Thread t3 = new Thread(runnable3);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}


class MyRunnable3 implements Runnable {
    Object obj = new Object();
    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            show();
        }
    }

    private synchronized void show() {//这里的锁就是 this
        if (ticket > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在售票" + (101 - ticket));
            ticket--;
        }
    }
}